package org.feng.enums;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;

import java.util.Arrays;
import java.util.Objects;

/**
 * 基础枚举接口
 *
 * @author fneg
 */
public interface BaseEnum<T> {

    T getValue();

    String getDesc();

    @SneakyThrows
    static <T> BaseEnum<T> of(String desc, Class<? extends Enum<?>> aClass) {
        if (aClass.isEnum()) {
            Enum<?>[] enumInstances = aClass.getEnumConstants();
            return Arrays.stream(enumInstances)
                    .map(instance -> {
                        if(instance instanceof BaseEnum) {
                            return (BaseEnum<T>) instance;
                        }
                       return null;
                    })
                    .filter(Objects::nonNull)
                    .filter(status -> StrUtil.equals(status.getDesc(), desc))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("desc " + desc + "对应的状态枚举不存在"));
        }

        return null;
    }

    @SneakyThrows
    static <T> BaseEnum<T> of(Integer value, Class<? extends Enum<?>> aClass) {
        if (aClass.isEnum()) {
            Enum<?>[] enumInstances = aClass.getEnumConstants();
            return Arrays.stream(enumInstances)
                    .map(instance -> {
                        if(instance instanceof BaseEnum) {
                            return (BaseEnum<T>) instance;
                        }
                        return null;
                    })
                    .filter(Objects::nonNull)
                    .filter(status -> Objects.equals(status.getValue(), value))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("value " + value + "对应的状态枚举不存在"));
        }

        return null;
    }
}
